﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Htse.Blue.Logic.Validation;
using Htse.Blue.Data;
using Htse.Blue.Models;
using System.Linq.Dynamic;

namespace Htse.Blue.Logic
{
	public class CarService :
		ServiceBase<Car, int, ICarRepository>,
		ICarService
	{
		public CarService(IValidationDictionary<Car> validationDictionary)
			: this(validationDictionary, new CarRepository())
		{
		}

		public CarService(
			IValidationDictionary<Car> validationDictionary,
			ICarRepository carRepository)
			: base(validationDictionary, carRepository)
		{
		}

		#region ICarService Members

		public PagedList<Car> ListForUmpire(int umpireId, int? page, int pageSize, string sortingParameter)
		{
			var cars = repository.GetAll(c => c.UmpireId == umpireId);

			if (string.IsNullOrEmpty(sortingParameter))
			{
				return cars.ToPagedList(page, pageSize);
			}
			else
			{
				return cars.OrderBy(sortingParameter).ToPagedList(page, pageSize, sortingParameter);
			}
		}

		#endregion

		protected override void ValidateAlways(
			Car entityToValidate,
			IValidationDictionary<Car> validationDictionary)
		{
			if (entityToValidate.LicensePlate.Length == 0)
			{
				validationDictionary.AddError(c => c.LicensePlate, "La targa è obbligatoria");
			}
			if (entityToValidate.BrandName.Length == 0)
			{
				validationDictionary.AddError(c => c.BrandName, "La marca è obbligatoria");
			}
			if (entityToValidate.ModelName.Length == 0)
			{
				validationDictionary.AddError(c => c.ModelName, "Il modello è obbligatorio");
			}
		}
	}
}
